<template>
  <el-row type="flex" align="middle" class="form-item">
    <!-- label -->
    <el-row class="item-label" justify="end">
      <el-row v-if="schema.option?.required" type="flex" class="required"> * </el-row>
      {{ schema.label }}
    </el-row>
    <!-- value -->
    <el-row class="item-value">
      <el-select
        v-model="dtoValue"
        v-bind="schema.option"
        :class="[validTips ? 'component valid-border' : 'component']"
        @change="onChange"
      >
        <el-option 
            v-for="item in schema.option?.enumList" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value" />
      </el-select>
    </el-row>
    <!-- tips -->
    <el-row v-if="validTips" class="valid-tips">
      {{ validTips }}
    </el-row>
  </el-row>
</template>
<script setup>
import { ref, toRefs, onMounted, watch, inject } from 'vue';
const ajv = inject('ajv');
const props = defineProps({
  schemaKey: String,
  schema: Object,
  model: [Number, String, Array],
});
const name = ref('select');
const emit = defineEmits(['field-change']);
const { schemaKey, schema } = props;
const { model } = toRefs(props);
const validTips = ref(null);
const dtoValue = ref();
const initData = () => {
  dtoValue.value = model.value ?? schema.option?.default;
};
onMounted(() => {
  initData();
});
watch(
  [model, schema],
  () => {
    initData();
  },
  { deep: true },
);
/**
 * 校验
 */
const validate = () => {
  validTips.value = null;
  // 校验是否必填
  if (schema.option?.required && !dtoValue.value) {
    validTips.value = '不能为空';
    return false;
  }
  // ajv 校验schema
  if (dtoValue.value) {
    let dtoEnum = [];
    if (schema.option?.enumList) {
      dtoEnum = schema.option.enumList.map((item) => item.value);
    }
    const ajvValidate = ajv.compile({ schema, ...{ emun: dtoEnum } });
    const valid = ajvValidate(dtoValue.value);
    if (!valid && ajvValidate.errors && ajvValidate.errors[0]) {
      const { keyword } = ajvValidate.errors[0];
      if (keyword === 'enum') {
        validTips.value = `取值超出枚举范围`;
      } else {
        console.log(ajvValidate.errors[0]);
        validTips.value = '不符合要求';
      }
      return false;
    }
  }
  return true;
};
/**
 * 获取组件值
 */
const getValue = () => {
  return dtoValue.value != undefined ? { [schemaKey]: dtoValue.value } : {};
};
const onChange = (value) => {
  let isValidate = validate();
  if (isValidate) {
    emit('field-change', { fieldName: schemaKey, value });
  }
};

defineExpose({
  validate,
  getValue,
  name,
});
</script>
<style scoped lang="less"></style>